package cn.itcast.anli.web;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建图片对象
        int width = 100;
        int height = 50;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //美化图片
        //- 填充图片背景色
        Graphics graphics = image.getGraphics();//获取图片的画笔对象
        graphics.setColor(Color.pink);//设置画笔颜色为粉红
        graphics.fillRect(0, 0, width, height);//用画笔对象将图片背景色填充为画笔的颜色
        graphics.setColor(Color.blue);//设置画笔颜色为蓝色
        graphics.drawRect(0, 0, width - 1, height - 1);//用蓝色画笔为矩形图片画一个边框

        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        //新建一个StringBuffer用于接收生成的验证码
        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        for (int i = 0; i < 4; i++) {
            int index = r.nextInt(str.length());
            //获取字符
            char ch = str.charAt(index);
            sb.append(ch);
            //写字符
            graphics.setFont(new Font("宋体",Font.BOLD,30));
            graphics.drawString(ch + "", (20 * i+10), 35);
        }
        //将sb转换为String类型
        String code = sb.toString();
        //将验证码code存入session中
        HttpSession session = request.getSession();
        session.setAttribute("checkcode",code);
        //在图片上画十条随随机线
        graphics.setColor(Color.GREEN);
        for (int i = 0; i < 10; i++) {
            int x1 = r.nextInt(width);
            int x2 = r.nextInt(width);

            int y1 = r.nextInt(height);
            int y2 = r.nextInt(height);

            graphics.drawLine(x1, y1, x2, y2);

        }


        //将图片输出到页面展示
        boolean jpg = ImageIO.write(image, "jpg", response.getOutputStream());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
